package cn.jekun.shop.common.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.DateJsonValueProcessor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.ErpMessage;
import cn.jekun.component.core.service.gen.ErpMessageService;
import cn.jekun.shop.app.bean.ShopMessage;

@Service(MessageService.BEAN_NAME)
public class MessageService extends ShopBaseService{
	
	public static final String BEAN_NAME = "cn.jekun.shop.common.service.MessageService";
	
	@Override
	public String getNamespace() {
		return "SHOP_MESSAGE";
	}
	
	@Resource(name = ErpMessageService.BEAN_NAME)
	ErpMessageService erpMessageService;
	
	/**
	 * 倒叙分页返回商家用户消息
	 * @param userId
	 * @param shopId
	 * @param type 1表示用户获取 2 表示商家获取
	 * @param page
	 * @return
	 */
	public JSONObject getMessages(
			@Security
			String userId, 
			@Security
			String shopId,
			@Security
			String type, 
			Page page) {
		JSONObject jsonObject = new JSONObject();
		//基本验证
		if(StringUtils.isBlank(userId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"用户代码不能为空");
		}
		if(StringUtils.isBlank(shopId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家代码不能为空");
		}
		try{
			Map map = new HashMap();
			map.put(ErpMessage.COL_USER_ID, userId);
			map.put(ErpMessage.COL_SHOP_ID, shopId);
			SqlUtis.prepareSql(map
					,SqlUtis.getSQLRequired(map, ErpMessage.COL_USER_ID)
					,SqlUtis.getSQLRequired(map, ErpMessage.COL_SHOP_ID)
					,SqlUtis.orderBy(ErpMessage.COL_CREATE_TIME +" desc nulls last")
					);
			List<ErpMessage> messages = erpMessageService.list(map, page);//获取消息
			//把消息更改为已读
			Map updateMap = new HashMap();
			updateMap.put(ErpMessage.COL_USER_ID, userId);
			updateMap.put(ErpMessage.COL_SHOP_ID, shopId);
			SqlUtis.prepareSql(updateMap
					,SqlUtis.getSQLRequired(updateMap, ErpMessage.COL_USER_ID)
					,SqlUtis.getSQLRequired(updateMap, ErpMessage.COL_SHOP_ID)
					, "1".equals(type)?" and a."+ErpMessage.COL_USER_READ+" is null" : " and a."+ErpMessage.COL_SHOP_READ+" is null"
					);
			ErpMessage erpMessage = new ErpMessage();
			if("1".equals(type)){
				erpMessage.setUserRead("1");
			}else{
				erpMessage.setShopRead("1");
			}
			updateMap.put("erpMessage", erpMessage);
			this.erpMessageService.update(updateMap);
			
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss")); 
			
			jsonObject.put("messages", JSONArray.fromObject(messages,jsonConfig));
			jsonObject.put("totalCount", page.getTotalCount());
			jsonObject.put("pages", page.getPages());
			return this.executeRerutn(jsonObject);
		}catch(BusinessException e){
			throw e;
		}catch(Exception e){
			e.printStackTrace();
		}
		return this.executeRerutnFail(jsonObject);
	}
	/**
	 * 用户发送给消息给商家
	 * @param userId 用户代码
	 * @param shopId 商家代码
	 * @param content 内容
	 * @return
	 */
	@Transactional
	public JSONObject sendMessage(
			@Security
			String userId, 
			@Security
			String shopId, 
			@Security
			String content) {
		JSONObject jsonObject = new JSONObject();
		//基本验证
		if(StringUtils.isBlank(userId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"用户代码不能为空");
		}
		if(StringUtils.isBlank(shopId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家代码不能为空");
		}
		if(StringUtils.isBlank(content)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"消息内容不能为空");
		}
		try{
			Map map = new HashMap();
			ErpMessage erpMessage = new ErpMessage();
			erpMessage.setContent(content);
			erpMessage.setCreateName(userId);
			erpMessage.setShopId(shopId);
			erpMessage.setType("1");//1表示用户发送给商家的消息
			erpMessage.setUserId(userId);
			map.put("erpMessage", erpMessage);
			
			erpMessageService.insert(map);//增加消息
			
			return this.executeRerutn(jsonObject);
		}catch(BusinessException e){
			throw e;
		}catch(Exception e){
			e.printStackTrace();
		}
		return this.executeRerutnFail(jsonObject);
	}
	/**
	 * 商家回复短信给用户
	 * @param userId 登录代码
	 * @param shopId 商家代码
	 * @param receiveUserId 接收用户代码
	 * @param content 内容
	 * @return
	 */
	@Transactional
	public JSONObject replyMessage(
			@Security
			String userId, 
			@Security
			String shopId, 
			@Security
			String receiveUserId, 
			@Security
			String content) {
		JSONObject jsonObject = new JSONObject();
		//基本验证
		if(StringUtils.isBlank(userId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"用户代码不能为空");
		}
		if(StringUtils.isBlank(shopId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家代码不能为空");
		}
		if(StringUtils.isBlank(receiveUserId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"接收用户代码不能为空");
		}
		if(StringUtils.isBlank(content)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"消息内容不能为空");
		}
		try{
			Map map = new HashMap();
			ErpMessage erpMessage = new ErpMessage();
			erpMessage.setContent(content);
			erpMessage.setCreateName(userId);
			erpMessage.setShopId(shopId);
			erpMessage.setType("2");//2表示用户发送给商家的消息
			erpMessage.setUserId(receiveUserId);
			map.put("erpMessage", erpMessage);
			
			erpMessageService.insert(map);//增加消息
			
			return this.executeRerutn(jsonObject);
		}catch(BusinessException e){
			throw e;
		}catch(Exception e){
			e.printStackTrace();
		}
		return this.executeRerutnFail(jsonObject);
	}
	public JSONObject getShopMessagers(
			@Security
			String shopId, 
			Page page) {
		JSONObject jsonObject = new JSONObject();
		//基本验证
		if(StringUtils.isBlank(shopId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家代码不能为空");
		}
		try{
			Map map = new HashMap();
			map.put("shop_id", shopId);
			List<ShopMessage> messages = this.list(map, page);//获取消息
			jsonObject.put("messages", messages);
			jsonObject.put("totalCount", page.getTotalCount());
			jsonObject.put("pages", page.getPages());
			return this.executeRerutn(jsonObject);
		}catch(BusinessException e){
			throw e;
		}catch(Exception e){
			e.printStackTrace();
		}
		return this.executeRerutnFail(jsonObject);
	}
	
}
